<template>
  <!-- 购物袋导航栏 -->
  <div class="box">
    <van-nav-bar
      title="购物袋"
      left-text="返回"
      left-arrow
      @click-left="gotoLogin"
      @click-right="editorStateChange()"
    >
      <template #right>
        <div>{{ rightText ? "完成" : "编辑" }}</div>
      </template>
    </van-nav-bar>
    <img class="auto-img" src="../assets/images/shopbag_bg.png" alt />
    <!-- 购物袋 -->
    <!-- 设置点击卡片时候的点击事件 -->
    <div class="product-item" v-for="(item,index) in shopbag" :key="index">
      <van-checkbox class="delete-button checkbox" v-model="item.isChecked" @click="judge()" />
      <van-swipe-cell  :before-close="beforeClose" @click="onClick($event, item)"  >
        <div class="product-box">
          <div class="img-box">
            <img :src="item.small_img"/>
          </div>
          <div class="context">
            <div class="head">
              <div class="name">{{ item.name }}</div>
              <div class="rule">{{ item.rule }}</div>
            </div>
            <div class="enname">{{ item.enname }}</div>
            <div class="tail">
              <div class="price">￥{{ item.price }}</div>
              <van-stepper
                theme="round"
                button-size="22"
                disable-input
                class="stepper"
                v-model="item.count"
                @change="countChange(item.sid, item.count)"
                onclick="event.cancelBubble = true"
              />
            </div>
          </div>
        </div>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="cancel(item)"/>
        </template>
      </van-swipe-cell>
    </div>
    <div class="noData">哎呀，没有数据可加载了！</div>
    <!-- 提交订单栏目 -->
    <div class="submitBox">
      <div class="left">
        <van-checkbox v-model="checked" @click="isSelectAll()">全选</van-checkbox>
      </div>
      <div class="middle" :class="rightText ? 'hidden' : 'block'">
        <span>合计：</span>
        <span class="span1">
          ￥
          <span class="totalPrice">{{ Math.floor(totalAccount) }}</span>
          .{{ fractionalPart }}
        </span>
      </div>
      <div class="right">
        <div class="submit-bar__button blue" v-if="!rightText" @click="onSubmit()">提交订单</div>
        <div class="submit-bar__button red" v-if="rightText" @click="onDelete()">删除选择</div>
      </div>
    </div>
  </div>
</template>


<script>
export default {
  name: "Shopbag",
  data() {
    return {
      shopbag_bg: require("../assets/images/shopbag_bg.png"),
      token: [],
      //存储购物袋中商品个数
      shopbagCount: [],
      //存储购物袋中商品数据
      shopbag: [],
      //判断是否全选
      checked: false,
      //商品总价
      totalAccount: "",
      //商品总价格小数部分
      fractionalPart: "00",
      //判断是否打开编辑模式
      rightText: false,
      isClick: false,
      // 被选择的sid
      sids: ""
    };
  },
  created() {
    this.token = localStorage.getItem("tk__");
    // this.getShopbagRows(),
    if (this.token != null) this.getShopbagData();
  },
  methods: {
    //获取购物车商品数据
    getShopbagData() {
      // console.log(this.token);
      this.axios({
        method: "GET",
        url: "/findAllShopcart",
        params: {
          appkey: this.appkey,
          tokenString: this.token
        }
      }).then(res => {
        this.shopbag = [];
        let dataMap = res.data.result;
        dataMap.map(v => {
          for (let i = 0; i < dataMap.length; i++) {
            v.isChecked = false;
            break;
          }
          this.shopbag.push(v);
        });
        console.log(res);
      });
    },
    //编辑切换
    editorStateChange() {
      this.rightText = !this.rightText;
                  this.calculate();
    },
    //返回登陆页面
    gotoLogin() {
      this.$router.push("/login");
    },
    //修改商品数量
    countChange(sids, counts) {
      this.axios({
        method: "POST",
        url: "/modifyShopcartCount",
        data: {
          appkey: this.appkey,
          tokenString: this.token,
          sid: sids,
          count: counts
        }
      }).then(res => {
        // console.log(res.data);
        this.calculate();
      });
    },
    //商品的点击事件
    onClick(events, item) {
      // console.log(events);
      switch (events) {
        case "cell":
          // console.log("跳转到"+item.name+"商品详情页面");
          this.$router.push({
            path: "/ProductDetail",
            query: { id: item.pid }
          });
          break;
      }
    },
    //右移商品后的点击事件
    beforeClose({ position, instance }) {
      switch (position) {
        case "cell":
          // console.log("跳转到商品详情页");
          break;
        case "outside":
          // console.log("点击外边");
          instance.close();
          break;
        case "right":
          console.log(this.sids);
          this.$dialog
            .confirm({
              message: "确定删除吗？"
            })
            .then(res => {
              this.axios({
                method: "POST",
                url: "/removeShopcart",
                data: {
                  appkey: this.appkey,
                  tokenString: this.token,
                  sids: this.sids
                }
              }).then(res => {
                console.log(res);
                if(res.data.code==7000)
                this.getShopbagData();
              });;
            })
            .catch(res => {
              //catch里面写取消后的事件
              // console.log(res); //cancel
            });
          break;
      }
    },
    // 得到点击事件的sid
    cancel(item){
      // console.log(item.sid);
      this.sids =JSON.stringify([item.sid]);
    },
    // 判断是否全选
    isSelectAll() {
      // console.log(this.checked);
      // console.log(this.shopbag.length);
      for (let j = 0; j < this.shopbag.length; j++) {
        // console.log(this.shopbag[j]);
        this.shopbag[j].isChecked = this.checked;
      }
      this.calculate();
    },
    //计算价格
    calculate() {
      this.totalAccount = 0.0;
      for (let j = 0; j < this.shopbag.length; j++) {
        if (this.shopbag[j].isChecked) {
          let count = this.shopbag[j].count;
          let price = this.shopbag[j].price;
          this.totalAccount += count * price;
          let splitPrice = this.totalAccount.toFixed(2).split(".");
          this.fractionalPart = splitPrice[1];
        }
      }
    },
    //判断选择一项商品之后是否为全选
    judge() {
      this.checked = true;
      for (let j = 0; j < this.shopbag.length; j++) {
        if (!this.shopbag[j].isChecked) this.checked = false;
      }
      this.calculate();
    },
    getSids() {
      var sidArr = [];
      for (var i in this.shopbag) {
        if (this.shopbag[i].isChecked) sidArr.push(this.shopbag[i].sid);
      }
      this.sids = JSON.stringify(sidArr);
    },
    //结算订单
    onSubmit() {
      this.getSids();
      if(this.sids!="[]"){
        this.$router.push({
            path: "/Order",
            query: { id:this.sids}
          });
        }
        else this.$toast("请选择商品进行结算");
    },
    //删除订单
    onDelete() {
      this.getSids();
      this.axios({
        method: "POST",
        url: "/removeShopcart",
        data: {
          appkey: this.appkey,
          tokenString: this.token,
          sids: this.sids
        }
      }).then(res => {
        console.log(res);
        if(res.data.code==7000)
        this.getShopbagData();
              this.calculate();
      });
    }
  }
};
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  padding-bottom: 150px;
  position: relative;
}
.goods-card {
  margin: 0;
  background-color: white;
}
/deep/ .van-swipe-cell {
  width: 100%;
}
.delete-button {
  height: 100%;
}
.product-item {
  display: flex;
  align-items: center;
  position: relative;
  margin: 10px 10px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}
.img-box {
  width: 80px;
  height: 100px;
  align-items: center;
}
.product-box {
  display: flex;
}
.img-box img {
  height: 80px;
  margin: 10px 0;
}
.context {
  margin: 10px;
  flex: 5;
}
.head,
.tail {
  display: flex;
  position: relative;
}
.stepper {
  align-self: flex-end;
  position: absolute;
  right: 10px;
}
.name {
  font-size: 13px;
}
.enname {
  margin: 13px 0;
  font-size: 10px;
  color: gray;
}
.price {
  color: #0c34ba;
  font-weight: bolder;
  font-size: 15px;
}
.rule {
  color: gray;
  font-size: 13px;
  margin-left: 10px;
}
.noData {
  text-align: center;
  margin: 20px 0;
  color: gray;
  font-size: 15px;
  height: 627px;
}
.submitBox {
  height: 50px;
  bottom: 50px;
  background-color: white;
  width: 100%;
  position: fixed;
  display: flex;
  align-content: space-between;
  padding: 0 16px;
  align-items: center;
}
.left {
  width: 56px;
}
.middle {
  width: 178px;
  text-align: right;
  line-height: 50px;
  font-size: 10px;
}
.right {
  width: 110px;
}
.checkbox {
  background: white;
  margin: 0 10px;
  width: 30px;
}
.span1 span {
  font-size: 20px;
}
.span1 {
  color: #0c34ba;
  padding-right: 12px;
}
.totalPrice {
  font-size: 30px;
}
.submit-bar__button {
  width: 110px;
  height: 40px;
  font-weight: 500;
  border: none;
  color: white;
  border-radius: 30px;
  text-align: center;
  line-height: 40px;
  font-size: 15px;
}
/deep/.van-stepper__minus {
  color: lightblue;
  border-color: lightblue;
}
/deep/.van-stepper__plus {
  color: white;
  background-color: #0c34ba;
}
.block {
  visibility: visible;
}
.hidden {
  visibility: hidden;
}
.blue {
  background: #0c34ba;
}
.red {
  background: red;
}
</style>>
